package org.dragonnova.meetingapp.app.fragment.guide;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.xys.libzxing.zxing.activity.CaptureActivity;

import org.dragonnova.meetingapp.R;
import org.dragonnova.meetingapp.utils.LogUtil;
import org.dragonnova.meetingapp.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Arrays;

public class WifiConnectFragment extends FragmentImpl implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private View mContentView;

    private ArrayList<String> mMessage;

    public WifiConnectFragment() {
        // Required empty public constructor
    }

    public static WifiConnectFragment newInstance(String param1, String param2) {
        WifiConnectFragment fragment = new WifiConnectFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_wifi_connect, container, false);
        initView();
        return mContentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initData();
    }

    @Override
    public void onStart() {
        super.onStart();
        LogUtil.eee("fragment start ==============================================================================================");
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
        LogUtil.eee("mparam1 = " + mParam1 + "/nmparam2 = " + mParam2);
        LogUtil.eee("fragment start ==============================================================================================");
    }

    public void initView() {
        Button mguide_bt_scan = (Button) mContentView.findViewById(R.id.mguide_bt_scan);
        Button mguide_bt_skip = (Button) mContentView.findViewById(R.id.mguide_bt_skip);

        mguide_bt_scan.setOnClickListener(this);
        mguide_bt_skip.setOnClickListener(this);
    }

    private void initData() {

    }

    // TODO: Rename method, updateMeeting argument and hook method into UI event
    public void interact(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 2;

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.mguide_bt_scan:
                if (ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CAMERA);
                } else {
                    Intent openCameraIntent = new Intent(getActivity(), CaptureActivity.class);
                    startActivityForResult(openCameraIntent, 0);
                }

                break;
            case R.id.mguide_bt_skip:
                Uri uri = Uri.parse("content://WifiConnectFragment" + "/" + "skip");
                interact(uri);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent openCameraIntent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);
            } else {
                // Permission Denied
                ToastUtil.showTip("授权失败");
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            if (!TextUtils.isEmpty(scanResult)) {
                String[] msg = scanResult.split(" ");
                if (msg.length == 2) {
                    mMessage = new ArrayList<>(Arrays.asList(msg));
                    Uri uri = Uri.parse("content://WifiConnectFragment" + "/" + "wifi" + "/" + mMessage.get(0) + "/" + mMessage.get(1));
                    interact(uri);
                } else {
                    Toast.makeText(getContext(), getString(R.string.prompt_wrong_qr_msg), Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), getString(R.string.prompt_wrong_qr_msg), Toast.LENGTH_SHORT).show();
            }
        }
    }
}
